<?php
namespace control;
/*
*仓位类
*/

class warehousePositionClass extends adIndexClass
{
    private const page = 'warehousePosition';
    private const table = 'warehouse_position';
    private const title = '仓位';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "{l.warehousePosition.home.orderNo}",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'aName' => [
                        'name'  => "{l.warehousePosition.home.wName}",
                        'width' => 200,
                    ],
                    'typeId'  => [
                        'name'  => "{l.warehousePosition.home.typeId}",
                        'width' => 150,
                    ],
                    'code'  => [
                        'name'  => '{l.warehousePosition.home.code}',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '{l.warehousePosition.home.name}',
                        'width' => 150,
                    ],
                    'barcode'         => [
                        'name'  => '{l.warehousePosition.home.barcode}',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '{l.warehousePosition.home.text}',
                        'width' => 200,
                    ],
                    'updateTime'          => [
                        'name'  => '{l.warehousePosition.home.updateTime}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '{l.warehousePosition.home.state}',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    lang('warehousePosition.home.orderNo') => text(array("name" => "orderNo")),
                    lang('warehousePosition.home.wName')   => text(array("name" => "wName")),
                    lang('warehousePosition.home.typeId') => selectMultiple(array("name" => "typeId",'table'=>'warehouse_type','where'=>"coid = '".self::$coid."' order by list asc",'sqlId'=>'id','sqlField'=>"name",'class'=>"width200")),
                ],
                [
                    lang('warehousePosition.home.code')  => text(array("name" => "code")),
                    lang('warehousePosition.home.name')  => text(array("name" => "name")),
                    lang('warehousePosition.home.state') => select(["name" => "state", 'option' => ['启用', '停用']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "b.orderNo" => $this->post('orderNo'),
            "b.name" => $this->post('wName'),
            "a.name" => $this->post('name'),
            "a.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.state" => $this->post('state'),//状态
            "a.coid"=>self::$coid
        );
        $and = "";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'code',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table.' as a join warehouse as b on a.orderId = b.id',
            'field'=>"a.*,b.orderNo,b.name as aName,b.typeId",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));

        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'typeId':
                        $row[] = warehouseClass::getTypeName($array['typeId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table.' as a join warehouse as b on a.orderId = b.id',
                    'field'=>"a.*,b.orderNo,b.name as aName,b.typeId",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by a.code desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '仓库编码'=>$array['orderNo'],
                            '仓库名称'=>$array['aName'],
                            '仓库分类'=>warehouseClass::getTypeName($array['typeId']),
                            '仓位编码'=>$array['code'],
                            '仓位名称'=>$array['name'],
                            '备注'=>$array['text'],
                            '更新日期'=>$array['updateTime'],
                            '状态'=>$array['state'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], lang('warehousePosition.home.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, lang('warehousePosition.home.fileName').".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }
    /**
     * 获取仓库名称
     * @param $id
     * @param bool $short
     * @param string $interval
     * @return mixed|string
     */
    public static function getName($id,$short = true,$interval = '-'){
        $query = query(self::table,"id = '$id'","id,code,name");
        if (empty($query['id'])){
            return '';
        }
        return $short?$query['name']:$query['code'].$interval.$query['name'];
    }
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'仓库编码',
                    'aliasName'=>'仓库编码',
                ],
                [
                    'columnName'=>'仓库名称',
                    'aliasName'=>'仓库名称',
                ],
                [
                    'columnName'=>'仓库分类',
                    'aliasName'=>'仓库分类',
                ],
                [
                    'columnName'=>'仓位编码',
                    'aliasName'=>'仓位编码',
                ],
                [
                    'columnName'=>'仓位名称',
                    'aliasName'=>'仓位名称',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
                [
                    'columnName'=>'更新日期',
                    'aliasName'=>'更新日期',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
            ]
        };
    }
}

